<template>
  <div>
    <div class="scrollable-container">
      <div class="scrollable-div">
      <span v-for="item in projectList" style="display: inline-block; padding: 10px;">
        <ImagePreview :width="150" :height="150" :src="item.projectImage"/>
        <div class="text">{{ item.projectName }}</div>
      </span>
        <span style="padding: 10px;">
        <el-button class="but" @click="handleAdd">
          <i class="el-icon-plus"></i>
        </el-button>
        <div class="text">新建项目</div>
      </span>
      </div>
    </div>
    <div ref="main" style="width: 100%; height: 600px;"></div>

    <!-- 添加或修改项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker clearable
                          v-model="form.startDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划进度" prop="projectPlan">
              <el-input-number v-model="form.projectPlan" placeholder="请输入计划进度"/>%
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际进度" prop="projectActual">
              <el-input-number v-model="form.projectActual" placeholder="请输入实际进度"/>%
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开业时间" prop="projectOpeningtime">
              <el-date-picker clearable
                              v-model="form.projectOpeningtime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择开业时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="竣工时间" prop="projectCompletetime">
              <el-date-picker clearable
                              v-model="form.projectCompletetime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择竣工时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="目标成本" prop="projectTargetCost">
          <el-input class="inputNum" type="number" v-model="form.projectTargetCost" placeholder="请输入目标成本"/>
          <span style="margin-left: 10px">约{{ formatCurrencyWithUnit(this.form.projectTargetCost) }}</span>
        </el-form-item>
        <el-form-item label="已付成本" prop="projectPaidCost">
          <el-input class="inputNum" type="number" v-model="form.projectPaidCost" placeholder="请输入已付成本"/>
          <span style="margin-left: 10px">约{{ formatCurrencyWithUnit(this.form.projectPaidCost) }}</span>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="logo" prop="projectLogo">
              <image-upload v-model="form.projectLogo" :limit="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="效果图" prop="projectImage">
              <image-upload v-model="form.projectImage" :limit="1"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//引入echarts
import * as echarts from 'echarts';
import {listProjectStatistics} from "@/api/prodata/projectStatistics";
import {addProject, listProject} from "@/api/project/project";

export default {
  name: "index",
  data() {
    return {
      //图表容器对象
      myChart: null,
      //图表各项属性
      option: null,
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
    }
  },
  mounted() {
    //1, 初始化图表容器
    this.myChart = echarts.init(this.$refs.main);

    //2, 图表各项属性
    this.option = {
      title: {
        text: '支付费用',
        left: 'left'
      },
      // 图例
      legend: {},
      tooltip: {},
      toolbox: {
        show: true,
        feature: {
          mark: {show: true},
          dataView: {show: true, readOnly: false},
          magicType: {show: true, type: ['line', 'bar']},
          restore: {show: true},
          saveAsImage: {show: true}
        }
      },
      xAxis: {
        name: '项目名称',
        type: 'category',
        data: [],
        axisLabel: {
          rotate: 45, // 根据需要调整旋转角度
        },
      },
      yAxis: {
        name: '费用',
        type: 'value',
        position: 'top',
      },
      series: [
        {
          name: '已付费用',
          data: [],
          type: 'bar',
          position: 'top',
          label: {show: true}
        },
        {
          name: '目标费用',
          data: [],
          type: 'bar',
          position: 'top',
          label: {show: true}
        },
      ]
    };

    //配置项
    this.myChart.setOption(this.option);
    this.getData()
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true;
      listProject().then(response => {
        this.projectList = response.data;
        console.log(response)
        console.log("*********response***********")
      });
    },
    getData() {
      listProjectStatistics().then((r) => {
        this.option.xAxis.data = r.data.projectNameList;
        this.option.series[0].data = r.data.paidList;
        this.option.series[1].data = r.data.targetList;
        this.option.series[0].label.formatter = function(params) {
          let paidAmounts = r.data.paidList;
          let paidAmount = paidAmounts[params.dataIndex];
          let formattedValue = paidAmount.toLocaleString('en-US', {
            // 最小精度
            minimumFractionDigits: 2,
            // 最大精度
            maximumFractionDigits: 2
          });

          // 定义单位转换
          const units = ['元', '万', '亿'];
          let unitIndex = 0; // 单位索引，默认为0
          // 数据大于一万且单位索引不会超过单位数组
          while (paidAmount >= 10000 && unitIndex < units.length - 1) {
            // 每4个0变一次单位
            paidAmount /= 10000;
            unitIndex++;
          }

          // 根据单位调整格式化后的数值，去除不需要的尾随零和小数点
          if (unitIndex > 0) {
            formattedValue = paidAmount.toLocaleString('en-US', {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2
            }).replace(/\.0+$/, ''); // 移除小数点后多余的零
            if (formattedValue.endsWith('.')) {
              formattedValue = formattedValue.slice(0, -1); // 如果小数点是最后一个字符，则移除它
            }
          }
          return `${formattedValue}${units[unitIndex] || ''}`;
        }
        this.option.series[1].label.formatter = function(params) {
          let targetAmounts = r.data.targetList;
          let targetAmount = targetAmounts[params.dataIndex];
          let formattedValue = targetAmount.toLocaleString('en-US', {
            // 最小精度
            minimumFractionDigits: 2,
            // 最大精度
            maximumFractionDigits: 2
          });

          // 定义单位转换
          const units = ['元', '万', '亿'];
          let unitIndex = 0; // 单位索引，默认为0
          // 数据大于一万且单位索引不会超过单位数组
          while (targetAmount >= 10000 && unitIndex < units.length - 1) {
            // 每4个0变一次单位
            targetAmount /= 10000;
            unitIndex++;
          }

          // 根据单位调整格式化后的数值，去除不需要的尾随零和小数点
          if (unitIndex > 0) {
            formattedValue = targetAmount.toLocaleString('en-US', {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2
            }).replace(/\.0+$/, ''); // 移除小数点后多余的零
            if (formattedValue.endsWith('.')) {
              formattedValue = formattedValue.slice(0, -1); // 如果小数点是最后一个字符，则移除它
            }
          }
          return `${formattedValue}${units[unitIndex] || ''}`;
        }

        this.myChart.setOption(this.option);
      }).catch(() => {})
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目";
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        addProject(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        projectName: null,
        projectPlan: null,
        projectActual: null,
        startDate: null,
        projectOpeningtime: null,
        projectCompletetime: null,
        projectTargetCost: 0,
        projectPaidCost: 0,
        projectLogo: null,
        projectImage: null,
        riskNum: null
      };
      this.resetForm("form");
    },
    formatCurrencyWithUnit(value) {
      let valueFloat = parseFloat(value);
      let formattedValue = valueFloat.toLocaleString('en-US', {
        // 最小精度
        minimumFractionDigits: 2,
        // 最大精度
        maximumFractionDigits: 2
      });

      // 定义单位转换
      const units = ['元', '万', '亿'];
      let unitIndex = 0; // 单位索引，默认为0
      // 数据大于一万且单位索引不会超过单位数组
      while (valueFloat >= 10000 && unitIndex < units.length - 1) {
        // 每4个0变一次单位
        valueFloat /= 10000;
        unitIndex++;
      }

      // 根据单位调整格式化后的数值，去除不需要的尾随零和小数点
      if (unitIndex > 0) {
        formattedValue = valueFloat.toLocaleString('en-US', {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2
        }).replace(/\.0+$/, ''); // 移除小数点后多余的零
        if (formattedValue.endsWith('.')) {
          formattedValue = formattedValue.slice(0, -1); // 如果小数点是最后一个字符，则移除它
        }
      }
      return `${formattedValue}${units[unitIndex] || ''}`;
    }
  }
}
</script>

<style scoped>
.scrollable-container {
  width: 100%;
  overflow-x: auto;
}

.scrollable-div {
  display: flex;
  flex-wrap: nowrap;
}

.text {
  text-align: center;
}

.but {
  width: 150px;
  height: 150px;
}

.el-icon-plus {
  font-size: 100px;
}
</style>
